﻿using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
using System.Security;
using System.Security.Cryptography;
using System.IO;

namespace Flickr2Frame
{
    public class StringEncryption
    {
        public string Encrypt(string str, string eightCharKey)
        {
            try
            {
                byte[] inputStr = ASCIIEncoding.ASCII.GetBytes(str);
                MemoryStream outputStream = new MemoryStream();
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                CryptoStream cryptoStream = null;
                des.Key = ASCIIEncoding.ASCII.GetBytes(eightCharKey);
                des.IV = ASCIIEncoding.ASCII.GetBytes(eightCharKey);
                cryptoStream = new CryptoStream(outputStream, des.CreateEncryptor(), CryptoStreamMode.Write);
                cryptoStream.Write(inputStr, 0, str.Length);
                cryptoStream.FlushFinalBlock();
                cryptoStream.Close();
                return Convert.ToBase64String(outputStream.ToArray());
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        public string Decrypt(string encryptedStr, string eightCharKey)
        {
            try
            {
                byte[] inputStr = Convert.FromBase64String(encryptedStr);
                MemoryStream inputStream = new MemoryStream(inputStr, 0, inputStr.Length);
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                CryptoStream cryptoStream = null;
                des.Key = ASCIIEncoding.ASCII.GetBytes(eightCharKey);
                des.IV = ASCIIEncoding.ASCII.GetBytes(eightCharKey);
                cryptoStream = new CryptoStream(inputStream, des.CreateDecryptor(), CryptoStreamMode.Read);
                return new StreamReader(cryptoStream).ReadToEnd();
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
    }
}